package com.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;



/**
 * 閫氱敤宸ュ叿绫�
 * 
 * @author liufeng
 * @date 2013-10-17
 */
public class CommonUtil {
	
	
	/**
     * 鑾峰彇绛惧悕
     * @param payInfo
     * @return
     * @throws Exception
     */
    public static String getSign(HttpServletRequest request, HttpServletResponse response ,RequestHandler reqHandler,String ip,String openId) throws Exception {
    	
    	String appid = com.bean.Constants.appid;
    	String mch_id= com.bean.Constants.mch_id;
    	
    	String nonce_str =  getNonce_str();
    	
		//鍟嗘埛璁㈠崟鍙�
		String out_trade_no = "A"+TenpayUtil.getCurrTime();
	
		String notify_url ="http://yxn.tunnel.qydev.com/Ambition/notify";
		
		String trade_type = "JSAPI";
		String openid = openId;
		
		
		//闈炲繀杈�
//		String product_id = "";
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);  
		packageParams.put("mch_id", mch_id);  
		packageParams.put("nonce_str", nonce_str);  
		packageParams.put("body", "my_xn_iphone");  
		packageParams.put("attach", "WeiXin_zf");  
		packageParams.put("out_trade_no", out_trade_no);  
		
		
		//杩欓噷鍐欑殑閲戦涓� 鍒嗗埌鏃朵慨鏀�
		packageParams.put("total_fee", "1");   
		packageParams.put("spbill_create_ip", ip);  
		packageParams.put("notify_url", notify_url);  
		
		packageParams.put("trade_type", trade_type);  
		packageParams.put("openid", openid);  

		String sign = reqHandler.createSign(packageParams);
		String xml="<xml>"+
				"<appid>"+appid+"</appid>"+
				"<mch_id>"+mch_id+"</mch_id>"+
				"<nonce_str>"+nonce_str+"</nonce_str>"+
				"<sign>"+sign+"</sign>"+
				"<body><![CDATA[my_xn_iphone]]></body>"+
				"<attach>WeiXin_zf</attach>"+
				"<out_trade_no>"+out_trade_no+"</out_trade_no>"+
				//閲戦锛岃繖閲屽啓鐨� 鍒嗗埌鏃朵慨鏀�
				"<total_fee>"+1+"</total_fee>"+
				//"<total_fee>"+finalmoney+"</total_fee>"+
				"<spbill_create_ip>"+ip+"</spbill_create_ip>"+
				"<notify_url>"+notify_url+"</notify_url>"+
				"<trade_type>"+trade_type+"</trade_type>"+
				"<openid>"+openid+"</openid>"+
				"</xml>";
       return xml;
    }
    
    public static String getNonce_str(){

    	String currTime = TenpayUtil.getCurrTime();
		//8浣嶆棩鏈�
		String strTime = currTime.substring(8, currTime.length());
		//鍥涗綅闅忔満鏁�
		String strRandom = TenpayUtil.buildRandom(4) + "";
		//10浣嶅簭鍒楀彿,鍙互鑷璋冩暣銆�
		String strReq = strTime + strRandom;
		
		return strReq;
    	
    }
	
	// 鍑瘉鑾峰彇锛圙ET锛�
	public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	/**
	 * 鍙戦�https璇锋眰
	 * 
	 * @param requestUrl 璇锋眰鍦板潃
	 * @param requestMethod 璇锋眰鏂瑰紡锛圙ET銆丳OST锛�
	 * @param outputStr 鎻愪氦鐨勬暟鎹�
	 * @return JSONObject(閫氳繃JSONObject.get(key)鐨勬柟寮忚幏鍙杍son瀵硅薄鐨勫睘鎬у�)
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			// 鍒涘缓SSLContext瀵硅薄锛屽苟浣跨敤鎴戜滑鎸囧畾鐨勪俊浠荤鐞嗗櫒鍒濆鍖�
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 璁剧疆璇锋眰鏂瑰紡锛圙ET/POST锛�
			conn.setRequestMethod(requestMethod);

			// 褰搊utputStr涓嶄负null鏃跺悜杈撳嚭娴佸啓鏁版嵁
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				// 娉ㄦ剰缂栫爜鏍煎紡
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 浠庤緭鍏ユ祦璇诲彇杩斿洖鍐呭
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			// 閲婃斁璧勬簮
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
		} catch (Exception e) {
		}
		return jsonObject;
	}

	/**
	 * 鑾峰彇鎺ュ彛璁块棶鍑瘉
	 * 
	 * @param appid 鍑瘉
	 * @param appsecret 瀵嗛挜
	 * @return
	 */
	
	
	/**
	 * URL缂栫爜锛坲tf-8锛�
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 鏍规嵁鍐呭绫诲瀷鍒ゆ柇鏂囦欢鎵╁睍鍚�
	 * 
	 * @param contentType 鍐呭绫诲瀷
	 * @return
	 */
	public static String getFileExt(String contentType) {
		String fileExt = "";
		if ("image/jpeg".equals(contentType))
			fileExt = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileExt = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileExt = ".amr";
		else if ("video/mp4".equals(contentType))
			fileExt = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileExt = ".mp4";
		return fileExt;
	}
}